package com.ruoyi.project.module.ordersHead.service;

import java.io.*;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.module.ordersDetail.domain.OrdersDetail;
import com.ruoyi.project.module.ordersDetail.mapper.OrdersDetailMapper;
import com.ruoyi.project.system.dict.domain.DictData;
import com.ruoyi.project.system.dict.mapper.DictDataMapper;
import com.ruoyi.project.system.user.domain.User;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.module.ordersHead.mapper.OrdersHeadMapper;
import com.ruoyi.project.module.ordersHead.domain.OrdersHead;
import com.ruoyi.project.module.ordersHead.service.IOrdersHeadService;
import com.ruoyi.common.support.Convert;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 上传的订单 服务层实现
 *
 * @author lcx
 * @date 2018-08-18
 */
@Transactional
@Service
public class OrdersHeadServiceImpl implements IOrdersHeadService {
    @Autowired
    private OrdersHeadMapper ordersHeadMapper;
    @Autowired
    private OrdersDetailMapper ordersDetailMapper;
    @Autowired
    private DictDataMapper dictDataMapper;

    /**
     * 查询上传的订单信息
     *
     * @param id 上传的订单ID
     * @return 上传的订单信息
     */
    @Override
    public OrdersHead selectOrdersHeadById(String id) {
        return ordersHeadMapper.selectOrdersHeadById(id);
    }

    /**
     * 查询上传的订单列表
     *
     * @param ordersHead 上传的订单信息
     * @return 上传的订单集合
     */
    @Override
    public List<OrdersHead> selectOrdersHeadList(OrdersHead ordersHead) {

        if (StringUtils.isNotEmpty(ordersHead.getSearchValue())) {
            String[] searchRow = {
                    "O.FileName"
            };
            return ordersHeadMapper.selectOrdersHeadListAsSearchRow(ordersHead, searchRow);
        } else {
            return ordersHeadMapper.selectOrdersHeadList(ordersHead);
        }
    }


    /*合计*/
    @Override
    public List<OrdersHead> selectSumCountOrdersHeadList(OrdersHead ordersHead) {
        if (StringUtils.isNotEmpty(ordersHead.getSearchValue())) {
            String[] searchRow = {
                    "O.FileName"
            };
            return ordersHeadMapper.selectOrdersHeadListAsSearchRowAsSum(ordersHead, searchRow);
        } else {
            return ordersHeadMapper.selectOrdersHeadListAsSum(ordersHead);
        }
    }

    /**
     * 新增上传的订单
     *
     * @param ordersHead 上传的订单信息
     * @return 结果
     */
    @Override
    public int insertOrdersHead(OrdersHead ordersHead) {
        return ordersHeadMapper.insertOrdersHead(ordersHead);
    }

    @Override
    public int insertOrdersHead(List<OrdersHead> list) {
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        return ordersHeadMapper.insertOrdersHeadByList(map);
    }

    /**
     * 修改上传的订单
     *
     * @param ordersHead 上传的订单信息
     * @return 结果
     */
    @Override
    public int updateOrdersHead(OrdersHead ordersHead) {
        return ordersHeadMapper.updateOrdersHead(ordersHead);
    }

    /**
     * 删除上传的订单对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteOrdersHeadByIds(String ids) {
        return ordersHeadMapper.deleteOrdersHeadByIds(Convert.toStrArray(ids));
    }

    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    @Override
    public int insertHeadAndDetail(String jsonList, String bz, User user) throws Exception {
        List<OrdersHead> ohList = JSONObject.parseArray(jsonList, OrdersHead.class);

        List<List<OrdersDetail>> odList = new LinkedList<List<OrdersDetail>>();

        for (OrdersHead ordersHead : ohList) {
            String fileUrl = ordersHead.getFileUrl();
            String fileName = ordersHead.getFileName();

            ordersHead.setId(UUID.randomUUID().toString());
            ordersHead.setCreateBy(user.getLoginName());
            ordersHead.setUpdateBy(user.getLoginName());
            ordersHead.setCompanyID(String.valueOf(user.getDeptId()));
            ordersHead.setOverseasStorageID("10501");
            ordersHead.setFileName(fileName);
            ordersHead.setFileUrl(fileUrl);

            //获取Excel行数
            fileUrl = RuoYiConfig.getProfile() + fileUrl;
            BufferedInputStream bis = null;
            bis = new BufferedInputStream(new FileInputStream(fileUrl));
            Integer counts = getExcleInfo(fileUrl, bis);
            bis.close();
            ordersHead.setCounts(counts);

            //读取Excel行记录
            bis = new BufferedInputStream(new FileInputStream(fileUrl));
            ExcelUtil excelUtil = new ExcelUtil(OrdersDetail.class);
            //订单信息List
            List<OrdersDetail> list = excelUtil.importExcel(fileName, bis);
            bis.close();
            for (OrdersDetail od : list) {
                od.setHeadId(ordersHead.getId());
            }
            odList.add(list);

            ordersHead.setBz(bz);
        }

        int ohResult = insertOrdersHead(ohList);

        List<DictData> dictData = dictDataMapper.selectDictDataByType("erp_order_status");
        for (int i = 0; i < odList.size(); i++) {
            List<OrdersDetail> odl = odList.get(i);
            for (int j = 0; j < odl.size(); j++) {
                OrdersDetail od = odl.get(j);

                od.setId(UUID.randomUUID().toString());
                od.setCreateBy(user.getLoginName());
                od.setUpdateBy(user.getLoginName());
                String companyId = String.valueOf(user.getDeptId());
                od.setCompanyID(companyId);
                od.setOverseasStorageID("10501");
                od.setLineNum(j+1);
                String orderStatus = od.getOrderStatus();
                od.setOrderStatus(getDictValueByLabel(orderStatus,dictData));
                od.setField1(orderStatus.trim());
            }
        }

        List<Map<String, Object>> list = new LinkedList<Map<String, Object>>();
        for (int i = 0; i < odList.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            List<OrdersDetail> l = odList.get(i);
            map.put("odList", l);
            list.add(map);
        }

        int odResult = ordersDetailMapper.insertOrdersDetailByList(list);
        return ohResult + odResult;
    }

    private String getDictValueByLabel(String label,List<DictData> list){
        for (DictData dictData : list){
            if(label.trim().equalsIgnoreCase(dictData.getDictLabel())){
                return dictData.getDictValue();
            }
        }

        return "";
    }

    private Integer getExcleInfo(String fileUrl, InputStream is) throws IOException {

        //HSSFWorkbook wb = new HSSFWorkbook(fis);
        XSSFWorkbook wb = new XSSFWorkbook(is);

        XSSFSheet sheet = wb.getSheetAt(0);
        CellReference cellReference = new CellReference("A4");

        boolean flag = false;
        for (int i = cellReference.getRow(); i <= sheet.getLastRowNum(); ) {
            XSSFRow r = sheet.getRow(i);
            if (r == null) {
                // 如果是空行（即没有任何数据、格式），直接把它以下的数据往上移动
                sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
                continue;
            }
            flag = false;
            for (Iterator cit = r.cellIterator(); cit.hasNext(); ) {
                XSSFCell c = (XSSFCell) cit.next();

                if (c.getCellType() != XSSFCell.CELL_TYPE_BLANK) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                i++;
                continue;
            } else {//如果是空白行（即可能没有数据，但是有一定格式）
                if (i == sheet.getLastRowNum())//如果到了最后一行，直接将那一行remove掉
                    sheet.removeRow(r);
                else//如果还没到最后一行，则数据往上移一行
                    sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
            }
        }

        return sheet.getLastRowNum();
    }
}
